<template>
  <ComDialog v-model="dialogVisible"
   :width="dialogWidth"
  :title="id ? '编辑' : '新增'">
    <ElementEasyForm ref="comFromRef" :formJson="formJson">
      <template #menuIds>
        <div>
                <div>
                  <el-checkbox
                    v-model="state.menuExpand"
                    @change="handleCheckedTreeExpand($event, 'menu')"
                    >展开/折叠</el-checkbox
                  >
                  <el-checkbox
                    v-model="state.menuNodeAll"
                    @change="handleCheckedTreeNodeAll($event, 'menu')"
                    >全选/全不选</el-checkbox
                  >
                  <el-checkbox
                    v-model="formJson.model.menuCheckStrictly"
                    @change="handleCheckedTreeConnect($event, 'menu')"
                    >父子联动</el-checkbox
                  >
                </div>
                <el-tree
                  class="tree-border"
                  :data="state.menuOptions"
                  show-checkbox
                  ref="treeRef"
                  node-key="id"
                  :check-strictly="!formJson.model.menuCheckStrictly"
                  empty-text="加载中，请稍候"
                  :props="state.defaultProps"
                ></el-tree>
              </div>
      </template>
    </ElementEasyForm>
    <template #footer>
	<div >
			<el-button size="large" @click="handleClose">取消</el-button>
			<el-button size="large" :loading="subLoading" type="primary" @click="submitData">保存</el-button>
		</div>
    </template>
    	
  </ComDialog>
</template>

<script setup lang="tsx">
import { ref, reactive, defineEmits, onMounted, watch, nextTick, shallowRef } from "vue";

import {
  getRole,
  addRole,
  updateRole,
  deptTreeSelect,
} from "/@ts/axios/urlApi/system/role";
import { dialogWidth, formItem } from "/@ts/enums/sizeEnum";
import { ElMessage } from "element-plus";
import { itemValue } from "/@ts/hooks/format";
import {
  treeselect as menuTreeselect,
  roleMenuTreeselect,
} from "/@ts/axios/urlApi/system/menu";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const emit = defineEmits(["update:modelValue","update"]);
const dialogVisible = shallowRef(false);
const subLoading = shallowRef(false);
const comFromRef = ref<any>();
// 所有菜单节点数据
const getMenuAllCheckedKeys = () => {
  // 目前被选中的菜单节点
  let checkedKeys = treeRef.value.getCheckedKeys();
  // 半选中的菜单节点
  let halfCheckedKeys = treeRef.value.getHalfCheckedKeys();
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
};
const submitData = async () => {
  try {

    const res = await comFromRef.value.validate();
    formJson.value.model.menuIds =  getMenuAllCheckedKeys();
    if (props.id) {
      updateRole(res).then((resItem: any) => {
        ElMessage.success(t("操作成功"));
        handleClose();
        emit("update");
      });
    } else {
      addRole(res).then((resItem: any) => {
        ElMessage.success(t("操作成功"));
        handleClose();
        emit("update");
      });
    }
  } catch (error) {
    console.log("error :>> ", error);
  }
};
const state = reactive({
  menuOptions:[],
  menuExpand: false,
  menuNodeAll: false,
});
const formJson = ref<any>({
   "rowAttrs": {
    "gutter":20,
    "justify": "start",
    "align": "middle"
  },
  schema: [
    {
      label: "角色名称",
      prop: "roleName",
      colAttrs: {
        span: 12,
      },
      componentName: "ElInput",
      attrs: {
        placeholder: "请输入",
      },
      rules: [{ required: true, message: "不能为空", trigger: 'change', }],
    },
      {
      label: "权限字符",
      prop: "roleKey",
      colAttrs: {
        span: 12,
      },
      componentName: "ElInput",
      attrs: {
        placeholder: "请选择",
      },
      rules: [{ required: false, message: "不能为空", trigger: 'change', }],
    },
       {
      label: "角色顺序",
      prop: "roleSort",
      colAttrs: {
        span: 12,
      },
      componentName: "ElInputNumber",
      attrs: {
        "placeholder": "请输入",
        "precision": 2,
        "controls-position": "right",
           ...formItem
      },
    
    },
    {
      label: "邮箱",
      prop: "email",
      colAttrs: {
        span: 12,
      },
      componentName: "ElInput",
      attrs: {
        type: "number",
        placeholder: "请选择",
      },
    
    },
    {
      label: "用户名称",
      prop: "userName",
      colAttrs: {
        span: 12,
      },
      componentName: "ElInput",
   
           hidden:{
         "matchPattern": "&&",
         "dataSelect":[],
        "type": "function",
        value:false,
        dataJs:(config,data)=>{
        return data.userId != undefined
      }
      },
      attrs: {
      
        placeholder: "请输入",
      },
    
    },
    {
      label: "状态",
      prop: "status",
      colAttrs: {
        span: 12,
        
      },
      componentName: "selectDict",
      attrs: {
        dictCode: "sys_normal_disable",
        placeholder: "请选择",
        showPassword: true,
      },
    
    },
    {
      label: "菜单权限",
      prop: "menuIds",
      colAttrs: {
        span: 12,
        
      },
      componentName: "ElInput",
      attrs: {
      
      },
    
    },
   
    {
      label: "备注",
      type: "COMPONENT",
      formItemAttrs: {},
      attrs: {
        placeholder: "请输入",
        type: "textarea",
      },
      rules: [],
      prop: "remark",
      componentName: "ElInput",
      colAttrs: {
        span: 24,
      },
    },
  ],

  model: {
  },
});
let props: any = defineProps({
  modelValue: {
    type: Boolean,
    defalut: false,
  },
  id: {
    type: String,
    defalut: "",
  },
});

const treeRef = ref();
const getMenuTreeselect = () => {
  menuTreeselect().then((response: any) => {
    state.menuOptions = response.data;
  });
}
const getInfo = () => {
  const roleMenu = getRoleMenuTreeselect(props.id);

  getRole(props.id).then((res: ResponseConfig) => {
    formJson.value.model = res.data;
    nextTick(() => {
      roleMenu.then((res: ResponseConfig) => {
        let checkedKeys = res.checkedKeys;
        checkedKeys.forEach((v: string) => {
          nextTick(() => {
            treeRef.value.setChecked(v, true, false);
          });
        });
      });
    });
  });
};
const getRoleMenuTreeselect = (roleId?: string): Promise<ResponseConfig> => {
  return roleMenuTreeselect(roleId).then((response: ResponseConfig) => {
    state.menuOptions = response.menus;
    return response;
  });
};
watch(
  () => props.modelValue,
  (val) => {
    dialogVisible.value = val;
    if(props.id&&val){
        getInfo();
      
    }else if(!props.id&&val){
      getMenuTreeselect()
      formJson.value.model = {
      };
    }
  },
  {
    immediate: true,
  }
);
// 树权限（展开/折叠）
const handleCheckedTreeExpand = (value: any, type: any) => {
  if (type == "menu") {
    let treeList = state.menuOptions;
    for (let i = 0; i < treeList.length; i++) {
      treeRef.value.store.nodesMap[treeList[i].id].expanded = value;
    }
  }
};
// 树权限（全选/全不选）
const handleCheckedTreeNodeAll = (value: any, type: any) => {
  if (type == "menu") {
    treeRef.value.setCheckedNodes(value ? state.menuOptions : []);
  } 
}
// 树权限（父子联动）
const handleCheckedTreeConnect = (value: any, type: any) => {
  if (type == "menu") {
    formJson.value.model.menuCheckStrictly = value ? true : false;
  } 
};
const handleClose = () => {
  emit("update:modelValue", false);
};
watch(
  () => dialogVisible.value,
  (val) => {
    if (!val) {
      handleClose();
    }
  }
);
</script>

<style scoped lang="scss"></style>
